package com.android.myapplication.util;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * 本地数据存取
 */

public class SPUtil {
    public final static String SHAREPREFERENCE_NAME = "test";

    /**
     * 存数据通用方法
     *
     * @param context
     * @param key
     * @param value
     */
    public static void putValue(Context context, String key, Object value) {
        SharedPreferences sp = context.getSharedPreferences(SHAREPREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        if (value instanceof String) {
            edit.putString(key, (String) value);
        } else if (value instanceof Integer) {
            edit.putInt(key, (int) value);
        } else if (value instanceof Boolean) {
            edit.putBoolean(key, (boolean) value);
        }
        edit.commit();
    }

    /**
     * 获取数据
     *
     * @param context
     * @param key
     * @param defaultValue
     */
    public static String getStringValue(Context context, String key, String defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(SHAREPREFERENCE_NAME, Context.MODE_PRIVATE);
        return sp.getString(key, defaultValue);
    }

    public static int getIntValue(Context context, String key, int defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(SHAREPREFERENCE_NAME, Context.MODE_PRIVATE);
        return sp.getInt(key, defaultValue);
    }

    public static boolean getBoolValue(Context context, String key, boolean defaultValue) {
        try {
            SharedPreferences sp = context.getSharedPreferences(SHAREPREFERENCE_NAME, Context.MODE_PRIVATE);
            return sp.getBoolean(key, defaultValue);
        } catch (Exception ex) {
            return defaultValue;
        }
    }



}
